package com.resafety.rtsp2flv.quartz.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.resafety.rtsp2flv.utils.ExecuteShellUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;



/**
 * @author gongl
 * @date 2023-03-22
 */
@Component
public class FlvMonitorTask {
    private static final Logger log = LoggerFactory.getLogger(FlvMonitorTask.class);
    @Autowired
    private ExecuteShellUtil executeShellUtil;
    @Value("${camera.stat-url}")
    private String stat;
    @Value("${camera.close-command}")
    private String closeCommand;
    @Value("${camera.open-command}")
    private String openCommand;

	//定时关闭无人观看的视频转码流
    @Scheduled(cron = "0 0/5 * * * ?")
    public void doTask() {
        JSONArray streams = getBody();
        streams.forEach(x -> {
            JSONObject object = (JSONObject) x;
            String name = object.getString("name");//摄像头编号,即转换配置的房间号
            JSONArray clients = object.getJSONArray("clients");
            if (clients.size() <= 1) {
                try {
                    executeShellUtil.execCmd(String.format(closeCommand, name));
                } catch (Exception e) {
                    log.error("关闭视频流异常---->" + e);
                }
            }
        });
    }
	//需要播放的视频是否已经在转码
    public void openStream(String stream) {
        JSONArray streams = getBody();
        boolean flag = true;
        for (Object x : streams) {
            JSONObject object = (JSONObject) x;
            String name = object.getString("name");
            if (stream.equals(name)) {
                flag = false;
                break;
            }
        }
        //若没有转码，则开始转码
        if (flag) {
            try {
            //根据stream摄像头编号得到摄像头的rtsp流地址
                executeShellUtil.execCmd(String.format(openCommand,"rtsp地址" , stream));
            } catch (Exception e) {
                log.error("启动视频流转换异常---->" + e);
            }
        }
    }
	//用于获取转码服务器在线的视频流及实时在线连接
    private JSONArray getBody() {
//        String body = RestTemplateUtils.get(stat, String.class).getBody();
//        JSONObject jsonObject = JSONObject.parseObject(body);
//        JSONObject httpFlv = jsonObject.getJSONObject("http-flv");
//        JSONObject server = httpFlv.getJSONArray("servers").getJSONObject(0);
//        JSONObject application = server.getJSONArray("applications").getJSONObject(0);
//        JSONObject live = application.getJSONObject("live");
//        return live.getJSONArray("streams");
        return null;
    }
}

